package com.neihanduanzi.utils;

import com.google.gson.Gson;
import com.neihanduanzi.database.DButil;
import com.neihanduanzi.database.RecommendDb;
import com.neihanduanzi.model.Comments;
import com.neihanduanzi.model.RecommendBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 凸显 on 2016/11/3.
 */

public final class JsonUtil {
    private JsonUtil() {
    }

    public static List<RecommendBean> getDataFromJson(String body) {
        List<RecommendBean> list=new ArrayList<>();
        if (body != null) {
            list.clear();
            DButil.deleteRecommend();
            try {
                JSONObject object = new JSONObject(body);
                JSONObject data = object.getJSONObject("data");
                JSONArray dataJSONArray = data.getJSONArray("data");
                Gson gson = new Gson();
                for (int i = 0; i < dataJSONArray.length(); i++) {
                    JSONObject jsonObject = dataJSONArray.getJSONObject(i);
                    int type = jsonObject.getInt("type");
                    if (type == 1) {
                        JSONObject group = jsonObject.getJSONObject("group");

                        RecommendDb recommendDb = new RecommendDb();
                        recommendDb.setRecommendGroup(group.toString());
                        DButil.addData(recommendDb);

                        RecommendBean recommendBean = gson.fromJson(group.toString(), RecommendBean.class);
                        JSONArray commentsArray = jsonObject.getJSONArray("comments");
                        if (commentsArray.length() == 1) {
                            JSONObject commentsJSONObject = commentsArray.getJSONObject(0);
                            Comments comments = gson.fromJson(commentsJSONObject.toString(), Comments.class);
                            recommendBean.setComments(comments);
                        }
                        list.add(recommendBean);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return list;
    }
}
